package jt.android.platformania.api;

import jt.android.platformania.api.GameThread;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

/// Main view, everything is drawn to GameView
public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
	private GameThread gameThread;
	private Point prevInput;
	
	public GameView(Context context, AttributeSet attributeset) 
	{
		super(context, attributeset);
		prevInput = new Point();
		
		// Allow this view to be focused
		setFocusable(true);
		
		// Initialize the main thread
		gameThread = new GameThread(this);
		
		// Get the surface holder and register it with the thread for drawing
		SurfaceHolder surfaceHolder = this.getHolder();
		surfaceHolder.addCallback(this);
		gameThread.registerSurfaceHolder(surfaceHolder);
	}
	
	public GameThread getGameThread()
	{
		return gameThread;
	}
	
	/// Called once the surface is ready to begin drawing
	public void surfaceCreated(SurfaceHolder surface)
	{
		// Register listener
		setOnTouchListener(gameThread);
		
		// Signal to run
		gameThread.setRunning();
		
		// Start the main thread
		gameThread.start();
	}

	/// Called if the surface is modified--this should never happen!
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) 
	{
		System.out.println("WARNING: Surface modified.  Format: " + format);
	}

	/// If this is called, the surface cannot be drawn to anymore
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		// Signal thread not to update
		gameThread.setTerminated();
		
		// Wait for thread to terminate
		boolean retry = true;
		while (retry)
		{
			try
			{
				gameThread.join();
				retry = false;		// No exception
				System.out.println("GameView: Thread stopped");
			}
			catch (InterruptedException e) {}
		}
	}
	
	public Point getPrevInput()
	{
		return prevInput;
	}
}
